'use strict';

const { setMenuActive } = require('../controller/utils');

module.exports = () => {
  return async function handleUrl(ctx, next) {
    let url = '';
    let targetURLNode = {};
    let urlArr = [];

    if (ctx.url.indexOf('/detail?') === -1) {
      url = ctx.url.split('?')[0];
      targetURLNode = findTargetURLNode(ctx.app.menus, url);
    } else {
      url = ctx.url.split('?')[0].split('detail')[0];
      urlArr = url.split('/');
      urlArr.pop();
      targetURLNode = findTargetURLNode(ctx.app.menus, urlArr.join('/'));
    }
    /**
     * @param {menu} menu menu数组
     * @param {targetURL} targetURL 需要高亮的目标
     * @return {menu} 将设置好的新menu返回
     */
    function findTargetURLNode(menu, targetURL) {
      const _menu = menu;
      let urlNode = {};
      let parentsNodes = {};
      const nodeArr = [];

      recursiveMenu(_menu, targetURL);
      // 递归menu，查找节点
      function recursiveMenu(menu, targetURL) {
        if (menu && menu.length > 0) {
          menu.forEach(element => {
            element.isActive = false;
            if (element.menu.href && element.menu.href === targetURL) {
              urlNode = element;
            } else if (element.children && element.children.length > 0) {
              recursiveMenu(element.children, targetURL);
            }
          });
        }
      }

      nodeArr.push(urlNode);
      // 根据节点，递归父辈节点
      if (urlNode.parentId !== '-1') {
        recursiveParentsNode(_menu, urlNode.parentId);
      }

      function recursiveParentsNode(menu, parentId) {
        if (menu && menu.length > 0) {
          menu.forEach(element => {
            if (element.id === parentId) {
              nodeArr.push(element);
              if (element.parentId !== '-1') {
                recursiveParentsNode(_menu, element.parentId);
              } else {
                parentsNodes = element;
              }
            } else if (element.children && element.children.length > 0) {
              recursiveParentsNode(element.children, parentId);
            }
          });
        }
      }
      return {
        urlNode,
        parentsNodes,
        nodeArr,
      };
    }

    for (let i = 0; i < targetURLNode.nodeArr.length; i++) {
      setMenuActive(targetURLNode.nodeArr[targetURLNode.nodeArr.length - 1].children, targetURLNode.nodeArr[i].label);
    }

    ctx.targetURLNode = targetURLNode;

    await next();
  };
};
